<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form :model="userForm" :rules="rulesUserForm" ref="userForm_">
        <el-form-item label="姓名" label-width="100px" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入名字"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div>
    </div>
    <div>
      <!-- 表格数据 -->
      <el-table :data="users" stripe border :highlight-current-row="true" height="560px">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center">
          <template slot="header" slot-scope="scope">
            姓名<el-input v-model="search" @change="searchName" size="medium" placeholder="输入关键字搜索" />
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column v-if="false" prop="status" label="状态" align="center" :formatter="showStatus"></el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template slot="header" slot-scope="scope">
            <el-select v-model="status" @change="searchStatus">
              <el-option value="全部">全部</el-option>
              <el-option value="正常">正常</el-option>
              <el-option value="封禁">封禁</el-option>
            </el-select>
          </template>
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" disable-transitions>{{
              scope.row.status === 1 ? '正常' : '封禁' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot="header" slot-scope="scope">
            <el-button type="success" @click="dialogVisible = true; userForm = {};title='新增用户'">新增</el-button>
            <el-button type="primary" @click="stautsAndName">联合查询</el-button>
          </template>
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="handleStatus(scope.$index, scope.row)">{{ scope.row.status ===
              1
              ? '禁用' : '启用' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" current-page.sync=1
        :current-page=pageInfo.currentPage :page-sizes="[5, 10, 15, 20]" :page-size=pageInfo.pageSize :page-count="7"
        :shide-on-single-page=true layout="total, sizes, prev, pager, next, jumper" :total=pageInfo.total>
      </el-pagination>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { getUsers, addUser, delUser,updateUserStatus } from '../api/users'
export default {
  name: 'User',
  data() {
    return {
      title:'',
      users: [],
      search: "",
      status: '全部',
      dialogVisible: false,
      userForm: {
        name: '',
        phone: '',
        email: '',
        status: 1
      },
      pageInfo: {
        total: 0,
        pageSize: 5,
        currentPage: 1
      },
      rulesUserForm: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          // { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        ],
      }
    };
  },
  mounted() {
    //获取所有用户
    var params = {
      "currentPage": this.pageInfo.currentPage,
      "pageSize": this.pageInfo.pageSize,
    }
    this.getUsersData(params)
    // this.users = [
    //   { id: 1, name: "a", phone: 110, email: "zhangsan@qq.com", status: 1 },
    //   { id: 2, name: "b", phone: 10086, email: "lisi@qq.com", status: 1 },
    //   { id: 3, name: "c", phone: 10086, email: "wangwu@qq.com", status: 0 },
    //   { id: 4, name: "d", phone: 10085, email: "zhaoliu@qq.com", status: 1 },
    //   { id: 5, name: "e", phone: 110, email: "zhangsan@qq.com", status: 1 },
    //   { id: 6, name: "f", phone: 10086, email: "lisi@qq.com", status: 1 },
    //   { id: 7, name: "g", phone: 10086, email: "wangwu@qq.com", status: 0 },
    //   { id: 8, name: "h", phone: 10085, email: "zhaoliu@qq.com", status: 1 },
    //   { id: 9, name: "i", phone: 110, email: "zhangsan@qq.com", status: 1 },
    //   { id: 10, name: "j", phone: 10086, email: "lisi@qq.com", status: 1 },
    //   { id: 11, name: "k", phone: 10086, email: "wangwu@qq.com", status: 0 },
    //   { id: 12, name: "l", phone: 10085, email: "zhaoliu@qq.com", status: 1 },
    //   { id: 13, name: "m", phone: 110, email: "zhangsan@qq.com", status: 1 },
    //   { id: 14, name: "n", phone: 10086, email: "lisi@qq.com", status: 1 },
    //   { id: 15, name: "o", phone: 10086, email: "wangwu@qq.com", status: 0 },
    //   { id: 16, name: "p", phone: 10085, email: "zhaoliu@qq.com", status: 1 },
    // ]
    // this.pageInfo.total = this.users.length
  },
  methods: {
    submitForm() {
      //在这里判断邮箱
      // const qq = /[1-9][0-9]+@qq.com/
      // if (qq.test(this.email)) {
      this.$refs.userForm_.validate((valid) => {
        if (valid) {
          console.log(this.userForm);

          //在这里进行springboot的ajax请求。添加user
          addUser(this.userForm).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type:'error',
                message:res.data.msg
              })
              console.log(res.data.code,res.data.msg);
              return;
            }
            this.$message({
                type:'success',
                message:res.data.msg
              })
          })
          // 提交表单页面并清空
          this.dialogVisible = false;
          this.userForm = {}
          //重新加载数据
          this.getUsersData(null)

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    showStatus(row, column, cellValue, index) {
      //用来转换状态  1 正常， 0 禁用
      if (cellValue == 1) {
        return '正常'
      } else {
        return '封禁'
      }
    },
    resetForm() {
      console.log('重置');
      this.userForm = {}
    },
    //用来处理编辑和删除的事件函数
    handleEdit(index, row) {
      this.dialogVisible = true
      this.title='编辑用户'
      //点击编辑回显 表单数据 ，这里用深拷贝
      this.userForm = JSON.parse(JSON.stringify(row))
    },
    handleDelete(index, row) {
      //删除要有提示
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row.id);
        //发送ajax请求，
        delUser(row.id).then(res => {
          console.log("发送了后端请求")
          if (res.data.code === 0) {
            this.$message({
                type:'error',
                message:res.data.msg
              })
            return;
          }
          this.$message({
                type:'success',
                message:res.data.msg
              })
        }).catch(error => {
          this.$message({
                type:'error',
                message:"请求接口出错"
              })
        })
        this.stautsAndName()
        // this.getUsersData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleStatus(index, row) {
      updateUserStatus(row.id,row.status === 1 ? 0 : 1).then(res => {
        console.log("发送了后端请求")
        if (res.data.code === 0) {
          this.$message({
                type:'error',
                message:res.data.msg
              })
          return;
        }
        this.$message({
                type:'success',
                message:res.data.msg
              })
      }).catch(error => {
        this.$message({
                type:'error',
                message:"请求接口出错"
              })
      })
      this.users[index].status = row.status === 1 ? 0 : 1
      this.stautsAndName()
      // this.getUsersData()
      console.log(row.status);
    },
    handleCurrentChange(value) {
      this.pageInfo.currentPage = value
      //传递当前页码。
      console.log(value)
      //发送分页请求
      this.stautsAndName()
    },
    handleSizeChange(value) {
      this.pageInfo.pageSize = value
      //传递当前每页大小
      this.stautsAndName()
      console.log(value)
    },
    searchName() {
      this.pageInfo.currentPage=1
      // 发送 关键字 请求。分页
      console.log(this.search, this.pageInfo.currentPage, this.pageInfo.pageSize)
      // var params = {
      //   "currentPage": this.pageInfo.currentPage,
      //   "pageSize": this.pageInfo.pageSize,
      //   'keywords': this.search
      // }
      // this.status='全部'
      // this.getUsersData()
      this.stautsAndName();
    },
    searchStatus(value) {
      this.pageInfo.currentPage=1
      var t = 1;
      if (value == "全部") {
        t = 2;
      } else if (value == "封禁") {
        t = 0;
      } else {
        t = 1;
      }
      var params = {
        "currentPage": this.pageInfo.currentPage,
        "pageSize": this.pageInfo.pageSize,
        'status': t,
        'keywords': this.search
      }
      // this.search=''
      this.getUsersData(params)
    },
    stautsAndName() {
      // this.pageInfo.currentPage=1
      var t = 1;
      if (this.status == "全部") {
        t = 2;
      } else if (this.status == "封禁") {
        t = 0;
      } else {
        t = 1;
      }
      if(this.search==""){
          var params = {
          "currentPage": this.pageInfo.currentPage,
          "pageSize": this.pageInfo.pageSize,
          'status': t,
        }
      }else{
        var params = {
          "currentPage": this.pageInfo.currentPage,
          "pageSize": this.pageInfo.pageSize,
          "keywords":this.search,
          'status': t,
        }
      }

      this.getUsersData(params)
    },
    getUsersData(params) {
      if (params == null) {
        params = {
          "currentPage": this.pageInfo.currentPage,
          "pageSize": this.pageInfo.pageSize,
          'status': 2,
          'keywords': this.search
        }
      }
      //发送ajax请求，获取users数据列表
      //获取用户列表
      getUsers(params).then(res => {
        console.log(res, "users数据")
        console.log("发送了后端请求")
        if (res.data.code === 0) {
          this.$message({
                type:'error',
                message:res.data.msg
              })
          return;
        }
        this.users = res.data.data.records
        this.pageInfo.total=Number(res.data.data.total)
        // console.log(res.data.records);
        // console.log(res.data.total);
      }).catch(error => {
        // 设置showError: false，可在此处单独设置错误提示
        this.$message({
          type: 'error',
          message: '请求接口出错'
        })
      })
    }
  }
}  
</script>
<style scoped></style>